package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo10 {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        System.out.println("请输入球员名字：");
        String name=scan.nextLine();
        System.out.println("请输入所属球队的名称：");
        String teamName=scan.nextLine();
        scan.close();
        //获取连接
        try (Connection conn=DBUtils.getConn()){
            //查询球队是否存在
            String sql="select id from team where name=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,teamName);
            //执行查询球队id的sql语句
            ResultSet rs=ps.executeQuery();
            int team_id=0;
            if (rs.next()){//球队存在
                team_id=rs.getInt(1);
            }else {//球队不存在
                //保存球队名称到team表
                String tsql="insert into team values(null,?)";
                PreparedStatement tps=conn.prepareStatement(
                        tsql, Statement.RETURN_GENERATED_KEYS);
                tps.setString(1,teamName);
                tps.executeUpdate();
                //取出装着自增id结果集的对象
                ResultSet trs=tps.getGeneratedKeys();
                trs.next();
                team_id=trs.getInt(1);
            }
            //保存球员
            String psql="insert into player values(null,?,?)";
            PreparedStatement pps=conn.prepareStatement(psql);
            pps.setString(1,name);
            pps.setInt(2,team_id);
            pps.executeUpdate();
            System.out.println("保存完成！");
        } catch (SQLException throwables) {
             throwables.printStackTrace();
        }
    }
}
